//
//  htvsamplequery.m
//  PHApp
//
//  Created by zhangwq on 16/4/11.
//  Copyright © 2016年 HT. All rights reserved.
//

#import "htvsamplequery.h"
#import "HTFrameKit.h"
#import "HTSysKit.h"
#import "HTFrameConvert.h"
#import "UIImageView+WebCache.h"

@interface htvsamplequery (){
    CGFloat width;
    CGFloat height;
    UIView *uv;
    NSMutableArray *sampleArray;
    int pageNum;//当前显示数据页 0/1:0表示刷新，1表示加载更多
    int page;
    UIColor *backcolor;
    UIColor *backcolor2;
    UIView *sampleview;
    CGFloat buttomHeight;
    UIView *chooseview;
    UITextField *txtkh;
    UITextField *txtzh;
    UITextField *txtxm;
    UIImageView *photo;
}

@property (nonatomic, strong) NSOperationQueue *queue;


@end

@implementation htvsamplequery

- (NSOperationQueue *)queue {
    if (!_queue) _queue = [[NSOperationQueue alloc] init];
    return _queue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    width = size.width;
    height = size.height;
    
    sampleArray=[NSMutableArray array];
    page=1;
    
    
    //上拉，下拉刷新
    
    
    self.tableView.pullDelegate = self;
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
    
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    
    self.tableView.separatorStyle=NO;
    
    backcolor=[UIColor colorWithRed:249.0/255.0 green:249.0/255.0 blue:249.0/255.0 alpha:1.0];
    
    backcolor2=[UIColor colorWithRed:180.0/255.0 green:180.0/255.0 blue:180.0/255.0 alpha:1.0];
    
    [self.searchview becomeFirstResponder];
    self.searchview.returnKeyType=UIReturnKeySearch;
    self.searchview.placeholder=@"搜索选样的客户";
    self.searchview.delegate=self;
    
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];


}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    sampleArray=[NSMutableArray array];
    [self bindList];
    [self.searchview resignFirstResponder];
    return YES;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)bindList{
    
    NSString *queryStr=@"";
    if(![self.searchview.text isEqualToString:@""]){
        queryStr=self.searchview.text;
    }
    
    NSString *serverUrl=[[NSString alloc]initWithFormat:@"%@\/%@\/",[HTSysParam erpServer],[HTSysParam erpVirDir]];
    HTFrameNet *htnet=[[HTFrameNet alloc] initWithServerUrl:serverUrl];
    NSString *pagenumStr=[[NSString alloc]initWithFormat:@"%i",page];
    NSDictionary *dict = @{@"queryStr":queryStr,@"pagernationVo": @{@"currPage":pagenumStr,@"pageSize": @10}};
    [htnet hmNetWCFmethodName:@"web/sample/queryDataSampleByQueryStr" andDic:dict complete:^(NSString *backstr)
     {
         
         
         NSDictionary *formdict=[HTFrameNet hmConvertDictFromJsonStr:backstr];//表单单头
         NSDictionary *body=[formdict objectForKey:@"body"];
         if(body!=nil){
             NSDictionary *resultdt2=[body objectForKey:@"DataSample"];
             NSMutableArray *resultdt=[resultdt2 objectForKey:@"data"];
             if (pageNum==0) {//刷新数据在头部插入
                 for (int i=[resultdt count]-1; i>=0; i--) {
                     [sampleArray insertObject:[resultdt objectAtIndex:i] atIndex:0];
                 }
             }
             else if (pageNum==1){//加载历史，在尾部插入
                 for (int i=0; i<[resultdt count]; i++) {
                     [sampleArray addObject:[resultdt objectAtIndex:i]];
                     
                 }
                 
             }
             
             if([resultdt count]==0&&page>1)
             {
                 page=page-1;
             }
             
             [self.tableView reloadData];
             
             sampleview.hidden=NO;
             
             
             
         }
         
         
     }];
    
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section==0){
        return 1;
    }
    else{
        return [sampleArray count];
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([indexPath section]==0){
        return 20.0;
    }
    else{
        if([indexPath row]<[sampleArray count]-1){
            return 130.0;
        }
        else{
            return 150.0;
        }
        
    }
}





- ( UITableViewCell *)tableView:( UITableView *)tableView cellForRowAtIndexPath:( NSIndexPath *)indexPath{
    
    NSString *cellId = @"cellname" ;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier :cellId];
    if (cell == nil ) {
        cell = [[ UITableViewCell alloc ] initWithStyle : UITableViewCellStyleDefault reuseIdentifier :cellId] ;
    }
    
    uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 130)];
    
    if([indexPath section]==0){
        uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 20)];
        uv.backgroundColor=[UIColor whiteColor];
        
        
        UIView *line=[[UIView alloc]initWithFrame:CGRectMake(20, 0, width, 20)];
        line.backgroundColor=[UIColor whiteColor];
        [uv addSubview:line];
    }
    else{
        if([indexPath row]<[sampleArray count]-1){
            uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 130)];
        }
        else{
            uv=[[UIView alloc]initWithFrame:CGRectMake(0, 0, width, 150)];
        }
        
        NSDictionary *dict=[[NSDictionary alloc]init];
        if([sampleArray count]>[indexPath row
                                ]){
            
            dict=[sampleArray objectAtIndex:[indexPath row]];
            
            UILabel *lbvendorname=[[UILabel alloc]initWithFrame:CGRectMake(120, 10, 200, 20)];
            lbvendorname.text=[[NSString alloc]initWithFormat:@"%@",[self checkValue:[dict objectForKey:@"vendorName"]] ];
            lbvendorname.textColor=[UIColor blackColor];
            lbvendorname.font=[UIFont fontWithName:@"Arial" size:14.0];
            [uv addSubview:lbvendorname];
            
            UILabel *lbformDate=[[UILabel alloc]initWithFrame:CGRectMake(width-100, 10, 100, 20)];
            lbformDate.text=[[NSString alloc]initWithFormat:@"%@",[self checkDate:[dict objectForKey:@"formDate"]] ];
            lbformDate.textColor=backcolor2;
            lbformDate.font=[UIFont fontWithName:@"Arial" size:10.0];
            lbformDate.textAlignment=UITextAlignmentRight;
            [uv addSubview:lbformDate];
            
            
            UILabel *lbcontactOPName=[[UILabel alloc]initWithFrame:CGRectMake(120, 40, 300, 20)];
            lbcontactOPName.text=[[NSString alloc]initWithFormat:@"联系人：%@",[self checkValue:[dict objectForKey:@"contactOPName"]] ];
            lbcontactOPName.textColor=backcolor2;
            lbcontactOPName.font=[UIFont fontWithName:@"Arial" size:12.0];
            [uv addSubview:lbcontactOPName];
            
            UILabel *lbcontactTel=[[UILabel alloc]initWithFrame:CGRectMake(120, 60, 300, 20)];
            lbcontactTel.text=[[NSString alloc]initWithFormat:@"联系电话：%@",[self checkValue:[dict objectForKey:@"contactTel"]] ];
            lbcontactTel.textColor=backcolor2;
            lbcontactTel.font=[UIFont fontWithName:@"Arial" size:12.0];
            [uv addSubview:lbcontactTel];
            
            UILabel *lbsaleOPID=[[UILabel alloc]initWithFrame:CGRectMake(120, 80, 300, 20)];
            lbsaleOPID.text=[[NSString alloc]initWithFormat:@"业务员：%@",[self checkValue:[dict objectForKey:@"saleOPID"]] ];
            lbsaleOPID.textColor=backcolor2;
            lbsaleOPID.font=[UIFont fontWithName:@"Arial" size:12.0];
            [uv addSubview:lbsaleOPID];
            
            
            
            UIImageView *iv=[[UIImageView alloc]initWithFrame:CGRectMake(30,15, 80,80)];
            iv.accessibilityLabel=@"http://7xshdz.com2.z0.glb.clouddn.com/20130827084459683.jpg";
            [iv setClipsToBounds:YES];
            [iv setContentMode:UIViewContentModeScaleAspectFill];
            iv.layer.masksToBounds=YES;
            iv.layer.cornerRadius = 4;
            iv.userInteractionEnabled=YES;
            [self downloadImg:iv];
            [uv addSubview:iv];
            
            
            
            
            
            
            UIView *line=[[UIView alloc]initWithFrame:CGRectMake(20, 110, width, 20)];
            line.backgroundColor=backcolor;
            [uv addSubview:line];
            
            
            UITapGestureRecognizer *cellGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sampledetailAction:)];
            cellGesture.accessibilityLabel=[dict objectForKey:@"id"];
            [uv addGestureRecognizer:cellGesture];
            
            
        }
        
    }
    
    
    
    
    
    
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.accessoryView=uv;
    
    
    
    return cell;
}



-(void)sampledetailAction:(UITapGestureRecognizer*)sender{
    NSString *storyboard=@"SampleDetail";
    NSString *Identifier=@"SampleDetail";
    UIStoryboard *valueView = [UIStoryboard storyboardWithName:storyboard bundle:nil];
    UIViewController *uv=[valueView instantiateViewControllerWithIdentifier:Identifier];
    [uv setValue:sender.accessibilityLabel forKey:@"formid"];
    UINavigationController *baNavigation = [[UINavigationController alloc] initWithRootViewController:uv];
    [self presentModalViewController:baNavigation animated:YES];
    
    //返回
}





-(NSString *)checkValue:(id)value{
    if(value==nil||value==[NSNull null]){
        return @"-";
    }
    else{
        return value;
    }
}

-(NSString *)checkDate:(id)value{
    NSString *datestr=@"-";
    NSArray *aTest = [value componentsSeparatedByString:@" "];
    if([aTest count]>0){
        datestr=[aTest objectAtIndex:0];
    }
    return datestr;
}




- (void)downloadImg:(UIImageView *)theImageView {
    
    NSString *imageName=[[NSString alloc]initWithFormat:@"%@?imageView2/2/w/200",theImageView.accessibilityLabel];
    NSURL *imagePath = [NSURL URLWithString:imageName];
    [self.queue addOperationWithBlock: ^{
        
        //在主线程中更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
            
            [theImageView sd_setImageWithURL:imagePath placeholderImage:[UIImage imageNamed:@"nopic"]];
            
            
            
        }];
    }];
}




#pragma 加载更多
//刷新数据
- (void) refreshTable
{
    pageNum=0;//刷新
    page=1;
    sampleArray=[NSMutableArray array];
    [self bindList];
    self.tableView.pullLastRefreshDate = [NSDate date];
    self.tableView.pullTableIsRefreshing = NO;
}


//加载更多数据
- (void) loadMoreDataToTable
{
    
    pageNum=1;//加载历史
    page=page+1;
    //读取服务端数据
    [self bindList];
    
    self.tableView.pullTableIsLoadingMore = NO;
    
}





#pragma mark - PullTableViewDelegate协议方法
-(void)pullTableViewDidTriggerRefresh:(PullTableView *)pullTableView
{
    @try {
        [self performSelector:@selector(refreshTable) withObject:nil afterDelay:1];
    }
    @catch (NSException *exception) {
        
        NSLog(@"HTINFO:%@",exception);
    }
    @finally {
    }
    
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    [self performSelector:@selector(loadMoreDataToTable) withObject:nil afterDelay:1];
}


- (IBAction)backAction:(UIButton *)sender {
    [self dismissViewControllerAnimated: YES completion: nil ];
}
- (IBAction)cancelAction:(UIButton *)sender {
    [self.searchview resignFirstResponder];
    [self dismissViewControllerAnimated: YES completion: nil ];
}
@end
